import '../../common/common.less';
import './index.less';
import '../../common/common.js';
import $tool from '../../common/tool.js'
import $store from '../../common/store.js'

$(function () {
  // var g = document.createElement('script');
  // g.type = 'text/javascript';
  // // g.async = true;
  // // g.defer = true;
  // g.src = 'https://apis.google.com/js/api:client.js';

  // var f = document.createElement('script');
  // f.type = 'text/javascript';
  // // f.async = true;
  // // f.defer = true;
  // f.src = 'https://connect.facebook.net/zh_TW/sdk.js';

  // var s = document.getElementsByTagName('script')[0];
  // s.parentNode.insertBefore(g, s);
  // s.parentNode.insertBefore(f, s);

  // setTimeout(() => {
  //   // 初始化gapi
  //   gapi.load('auth2', function() {
  //     var auth2 = gapi.auth2.init({
  //         client_id: '311192923957-dklnkq4vlc0fcrncbt37v1jkkbb1qvb1.apps.googleusercontent.com', //TODO: 到Google申请的
  //         // client_id: '311192923957-4biacdjmaudvi5gada8hbbm1l9kr2ajt.apps.googleusercontent.com', //TODO: 到Google申请的
  //         cookiepolicy: 'single_host_origin',
  //     });
  
  //     auth2.attachClickHandler(document.getElementById('loginGoogle'), {}, onSuccess, onFailure);
  //   });
  //   // 初始化FB
  //   window.fbAsyncInit = function() {
  //     FB.init({
  //       appId      : '249136313541020',
  //       cookie     : true,                     // Enable cookies to allow the server to access the session.
  //       xfbml      : true,                     // Parse social plugins on this webpage.
  //       version    : 'v10.0'           // Use this Graph API version for this call.
  //     });
  //   };
  // }, 500);
  /*********************************************************以上方式会造成js文件加载异常，不知道为什么我pc端正常，但是运营pc端出问题，可能和网络或浏览器有关，现已修改为从本地加载g.js和f.js文件**************************************************************************/

  //加载语言包
  $tool.loadProperties(res=>{
    let html = [];
    html.forEach(item=>{
        $("."+item).html($.i18n.prop(item))
    })
  });
  var type = $tool.getQuery('type');
  if(type == 1) {
    $('.login-middle').show();
    $('.login-right').show();
  }
  chooseLoginType();
  chooseServer();
  chooseRecharge();
  finish();
  logout();
  $('.facebook').click(function() {
    loginFB();
  });
  $('#loginpwd').click(function() {
    loginBypwd();
  });
  localStorage.setItem('paltform', getCurPaltform());
  var username = localStorage.getItem('username');
  var userId = localStorage.getItem('uid');
  if(username && userId) {
    initAccount();
    initUserRole();
    initRecharge();

    $('.card').show();
    $('.main-section').hide();
  } else {
    $('.card').hide();
    $('.main-section').show();
  }
})

/**********************************页面按钮事件方法start******************************************/
function chooseLoginType() {
  $('.btn-group').change(function (e) {
    var paltform = e.target.value;
    if(paltform == 'ios'){
      $('.google').hide();
      localStorage.setItem('paltform', paltform);
    } else if(paltform == 'android') {
      $('.google').show();
      $('.facebook').show();
      localStorage.setItem('paltform', paltform);
    } else {
      localStorage.setItem('paltform', '');
    }
  });
}

function chooseServer() {
  $("#server").change(function () {
    var curServerid = $('#server').val();
    if (curServerid) {
      getUserRoleInfoByCurServer(curServerid);
    }
  });
}

function chooseRecharge() {
  $("#recharge").change(function () {
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    $("#recharge_TWD").val(twd_price);
    $("#recharge_goods").val(goodsId_count);
  });
}

function logout() {
  $("#logout").on("click",async function(){
    localStorage.clear();
    $('.card').hide();
    $('.main-section').show();
    location.reload();
  });
}

function finish() {
  $("#finish").click(function () {
    var msg = form_validate();
    if (msg != true) {
      $tool.showError(msg);
      return;
    }
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    let $el = $tool.showconfim({
      text: '您即将花费Mycard ' + twd_price + '點, 获取' + goodsId_count + '靈玉',
      cancel_text: '取消',
      submit_text: '确定',
      cancelfn: () => {
        $el.fadeOut("fast")
      },
      submitfn: () => {
        $el.fadeOut("fast")
        var curUserId = $('#userId').val().trim();
        var curPrice = $("#recharge").val();
        var curRoleName = $("#role_name").val().trim();
        var curRoleId = $("#role_id").val().trim();
        var curServerName = $("#server").find("option:selected").text().trim();
        var curServerid = $('#server').val();
        getPayUrl(curUserId, curPrice, curRoleName, curRoleId, curServerName, curServerid);
      },
    })
  });
}

function getPayUrl(curUserId, curPrice, curRoleName, curRoleId, curServerName, curServerid) {
  var curPaltform = localStorage.getItem('paltform');
  var requestData = {
    userId: curUserId,
    goodsId: curPrice,
    roleName: curRoleName,
    roleId: curRoleId,
    serverName: curServerName,
    serverId: curServerid,
    paltform: curPaltform
  };
  $.get('/php/getPayUrl.php', requestData, function (response) {
    var res = JSON.parse(response);
    if (res.status == true) {
      window.open('http://' + res.data.payUrl);
      // mycard不支持内嵌方式
      // var ifrm = document.createElement("iframe");
      // var protocol = document.location.protocol;
      // ifrm.setAttribute("src", protocol + '//' + res.data.payUrl);
      // ifrm.style.width = "640px";
      // ifrm.style.height = "480px";
      // ifrm.style.width = "99%";
      // ifrm.style.height = "500px";
      // $('#recharge_iframe').html(ifrm);
    } else {
      $tool.showError('支付地址获取失败');
    }
  });
}
/**********************************页面按钮事件方法end******************************************/
/**********************************页面表单数据初始化方法start******************************************/
function initAccount() {
  var username = localStorage.getItem('username');
  var userId = localStorage.getItem('uid');
  if (username != null && username != undefined && username != '') {
    $('#username').val(username);
  }
  if (userId != null && userId != undefined && userId != '') {
    $('#userId').val(userId);
  }
  var bindFB = JSON.parse(localStorage.getItem('bindFB'));
  var bindGoogle = JSON.parse(localStorage.getItem('bindGoogle'));
  if (bindFB != null && bindFB !== undefined && bindFB.isBind) {
    $('#no_bind_fb').prop('checked', false);
    $('#bind_fb').prop('checked', true);
    $('#facebook_username').val(bindFB.otherAccountName || username);
  }
  if (bindGoogle != null && bindGoogle !== undefined && bindGoogle.isBind) {
    $('#no_bind_gg').prop('checked', false);
    $('#bind_gg').prop('checked', true);
    $('#google_username').val(bindGoogle.otherAccountName || username);
  }
}

function initUserRole() {
  var curPaltform = localStorage.getItem('paltform');
  var username = localStorage.getItem('username');
  var userId = localStorage.getItem('uid');
  var requestRoleData = {
    username: username,
    uid: userId,
    paltform: curPaltform
  };
  $.get('/php/getUserRole.php', requestRoleData, function (response) {
    var res = JSON.parse(response);
    if (res.code == 200) {
      var userRoleDatas = res.data;
      initServers(userRoleDatas);
      initRoleServers(userRoleDatas);
      var curServerid = $('#server').val();
      if (curServerid != null && curServerid != undefined && curServerid > 0) {
        getUserRoleInfoByCurServer(curServerid);
      }
    }
  });
}

function initServers(userRoleDatas) {
  var serverData = [];
  for (var i in userRoleDatas) {
    var userRoleData = userRoleDatas[i];
    var server_id = userRoleData.serverId;
    var server_name = userRoleData.serverName;
    serverData.push({
      "server_id": server_id,
      "server_name": server_name
    });
  }
  var serverSelect = document.getElementById("server");
  serverSelect.options.length = 0;
  for (var i = 0; i < serverData.length; i++) {
    //先创建好select里面的option元素
    var option = document.createElement("option");
    //转换DOM对象为JQ对象,好用JQ里面提供的方法 给option的value赋值
    $(option).val(serverData[i].server_id);
    //给option的text赋值,这就是你点开下拉框能够看到的东西
    $(option).text(serverData[i].server_name);
    //获取select 下拉框对象,并将option添加进select
    serverSelect.options.add(option);
  }
  localStorage.setItem('serverData', JSON.stringify(serverData));
}

function initRoleServers(userRoleDatas) {
  var userRoleMap = new Map();
  for (var i in userRoleDatas) {
    var userRoleData = userRoleDatas[i];
    var server_id = userRoleData.serverId;
    var server_name = userRoleData.serverName;
    userRoleMap.set(server_id, userRoleData);
  }
  var obj = MapToObj(userRoleMap);
  localStorage.setItem('userRoleData', JSON.stringify(obj));
}

function initRecharge() {
  $.get("/php/getProducts.json", {}, function(response) {
    var res = response;
    var productsData = res.data;
    var rechargeSelect = document.getElementById("recharge");
    rechargeSelect.options.length = 0;
    for (var i = 0; i < productsData.length; i++) {
      //先创建好select里面的option元素
      var option = document.createElement("option");
      //转换DOM对象为JQ对象,好用JQ里面提供的方法 给option的value赋值
      $(option).val(productsData[i].goodsId);
      //给option的text赋值,这就是你点开下拉框能够看到的东西
      $(option).text(productsData[i].product_name);
      //自定义属性商品Id
      $(option).attr("twd_price", productsData[i].twd_price);
      //自定义属性商品数量
      $(option).attr("goodsId_count", productsData[i].goodsId_count);
      //获取select 下拉框对象,并将option添加进select
      rechargeSelect.options.add(option);
    }
    var twd_price = $("#recharge").find("option:selected").attr('twd_price');
    var goodsId_count = $("#recharge").find("option:selected").attr('goodsId_count');
    $("#recharge_TWD").val(twd_price);
    $("#recharge_goods").val(goodsId_count);
  });
}

function getUserRoleInfoByCurServer(curServerid) {
  var userRoleData = JSON.parse(localStorage.getItem('userRoleData'));
  if (userRoleData != null && userRoleData != undefined && userRoleData != '{}') {
    var userRoleData_ = ObjToMap(userRoleData);
    var UserRoleInfo = userRoleData_.get(curServerid);
    if (UserRoleInfo != null && UserRoleInfo != undefined && UserRoleInfo != '') {
      $("#role_name").attr("value", UserRoleInfo.roleName);
      $("#role_id").attr("value", UserRoleInfo.roleId);
      $("#role_level").attr("value", UserRoleInfo.roleLevel);
    }
  }
}
/**********************************页面表单数据初始化方法end******************************************/
/**********************************facebook登录start******************************************/
window.fbAsyncInit = function() {
  FB.init({
    appId      : '249136313541020',
    cookie     : true,                      // Enable cookies to allow the server to access the session.
    xfbml      : true,                      // Parse social plugins on this webpage.
    version    : 'v10.0'                    // Use this Graph API version for this call.
  });
};
function loginFB() {
  FB.login(function(response){
    // console.log(response);
    // {
    //   "authResponse": {
    //       "accessToken": "EAADilpF4IZAwBAOCdTZA71BMA4HqzwdWPczfzZBZBud7kJFNLoAPATLxBdObQ5QU1i2FrGTGdg9hI3CPrNgZCii0k1qWtkiBS6ITeWkEZCLgnTqSn2Y56wc3UWEUbAhZBXk7JKQAIBUe3w80zGquY9y3gYBLoP2SjHzU94fa2svjVzxZA8kFLb2RQWNHFVq2VhkkIEed7XFfxQZDZD",
    //       "userID": "1406200653064977",
    //       "expiresIn": 7153,
    //       "signedRequest": "3OjCcffoyrBN7sWs5_NHZ87hsHDySjKaKJU3oJRqDZA.eyJ1c2VyX2lkIjoiMTQwNjIwMDY1MzA2NDk3NyIsImNvZGUiOiJBUUN6Q0dDVlhNdW1XY2NxcFhjUkZ1LVBOeW1fU2tQckZ0dnFfYzV2S2hmSFBYZ0x4dVZ1Uk9iRWUya1hGOFYyT1VqV0Q0dEhCOFBCUGlVX0FlNGRELXV6SHJxdFBaNjVWbHptZ3Z1ZjRrZGh1SW1JT1dQNW5TcUtsQ1NiZ3BYVzFjS01fYTdZQlA4T014V1lmQ3lITnhvVjZxSkpwcnQ0YWo0a19xVUt4SkNNcXBNLUxoQWpHUXRsZWRHc0VGVXkxY2NFa3AwNG8ycXhpa2t2czlpeEs3YXF3OWFOdHktVUtKdDZpbTNVZFhQazZqUFc1WkN5djNkaE9nNE94c01ZRml1RFdWZmlTRVJUcDFqX0pIYTBsaHh4ckwxMVZPWXFrQV9TdXRINGZuOTIyclhKZWxZNVRIQlVTcEZBUjN2YmozaF9GcGR2MlhvR0c1WlhvWHlDdEotSEFnejBwc3prNTI2NEJxeUFfMEgtcEEiLCJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTYxNjc1Mjg0N30",
    //       "graphDomain": "facebook",
    //       "data_access_expiration_time": 1624528847
    //   },
    //   "status": "connected"
    // }
    if (response.status === 'connected') {
      login(response.authResponse, 6); 
    } else {
      $tool.showError('please login by facebook!');
    }
 });
}
/**********************************facebook登录end******************************************/
/**********************************google登录start******************************************/
gapi.load('auth2', function() {
  var auth2 = gapi.auth2.init({
    client_id: '311192923957-dklnkq4vlc0fcrncbt37v1jkkbb1qvb1.apps.googleusercontent.com', //TODO: 到Google申请的
    cookiepolicy: 'single_host_origin',
  });
  auth2.attachClickHandler(document.getElementById('loginGoogle'), {}, onSuccess, onFailure);
});
function onSuccess(googleUser) {
  // console.log(googleUser);
  // {
  //   "Aa": "106186996154558463175",
  //   "tc": {
  //       "token_type": "Bearer",
  //       "access_token": "ya29.a0AfH6SMADErT_Rme1JjbRLKpMuNcWxA0I6PoZXqCn0LA3srcLiopcwJsQK2HbRnqYGz7l3GUqUP6VEwzopv_KRAsz8-24ovojKueDYO288DTPDJQgzE6Gfa5_SzdZmDvJtltSueiEAuNHOclpXjYELqIJU-U6",
  //       "scope": "email profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
  //       "login_hint": "AJDLj6JUa8yxXrhHdWRHIV0S13cAK4_DcLfKRJcMn_edfooZrvjHGp8aYh7CkWJOP3aydFZldR-JpU8FaQcXixXGRsI8tTvRLw",
  //       "expires_in": 3599,
  //       "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImUxYWMzOWI2Y2NlZGEzM2NjOGNhNDNlOWNiYzE0ZjY2ZmFiODVhNGMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMzExMTkyOTIzOTU3LWRrbG5rcTR2bGMwZmNybmNidDM3djFqa2tiYjFxdmIxLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXVkIjoiMzExMTkyOTIzOTU3LWRrbG5rcTR2bGMwZmNybmNidDM3djFqa2tiYjFxdmIxLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwic3ViIjoiMTA2MTg2OTk2MTU0NTU4NDYzMTc1IiwiZW1haWwiOiJkb2Rqb3kwM0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IlZYR25kWkxFU1ZiaFE3UVBCYlhEaWciLCJuYW1lIjoiMDMgZG9kam95IiwicGljdHVyZSI6Imh0dHBzOi8vbGg1Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tek02QjE0bmZFYTgvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQUEvQU1adXVjbnJtcnliS3FLd1JKbTdwY3pnNGtCeXc0MkNYZy9zOTYtYy9waG90by5qcGciLCJnaXZlbl9uYW1lIjoiMDMiLCJmYW1pbHlfbmFtZSI6ImRvZGpveSIsImxvY2FsZSI6InpoLUNOIiwiaWF0IjoxNjE3ODcyNzk3LCJleHAiOjE2MTc4NzYzOTcsImp0aSI6IjQxZjQ3OGUzMzM1N2Q3MjZjMDEwYTNiOWExYjIwNzFlOTMxZmRkZmYifQ.el3AZwSOhTaU0-6Ld_arktjdSq8tboyRP8JyIyvU6dsXX5ewGUuJWoCm47H0AqMjlNyaU8DQv6CMKAc1upz_Q-Oi-XlGizRdKtZ6jNifOBeKmyhTBL3kf48Mats3ejfF5jSnvvFtlekvj3e_Kz_jwd5YsRnDLWoIj77g9cZMNyHk1nV-V2HbpYwtk4p7PCQtq8WPriZxWIlLC4H9kjt0_8Wk4PE5Wlpn_juvk-g_fbKLHRr5ZpfJwEQjTDEGsL7uLdDS3XMdnlzkQdP7c_NCl13sRMqSCkPhOMwMB60jAVKnU-drG_pew1lYN58izk53J9NnUe9MiHSsK5-JQtT83Q",
  //       "session_state": {
  //           "extraQueryParams": {
  //               "authuser": "0"
  //           }
  //       },
  //       "first_issued_at": 1617872797781,
  //       "expires_at": 1617876396781,
  //       "idpId": "google"
  //   },
  //   "Rs": {
  //       "RR": "106186996154558463175",
  //       "Se": "03 dodjoy",
  //       "BT": "03",
  //       "xR": "dodjoy",
  //       "WI": "https://lh5.googleusercontent.com/-zM6B14nfEa8/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucnrmrybKqKwRJm7pczg4kByw42CXg/s96-c/photo.jpg",
  //       "At": "dodjoy03@gmail.com"
  //   }
  // }
  // google登录不知道为什么变成下面这个数据了
  // {
  //   "Aa": "106186996154558463175",
  //   "qc": {
  //       "token_type": "Bearer",
  //       "access_token": "ya29.a0AfH6SMAsnekZvEAryiVvTM2j76SBCf0HIQGAiCt-6jNX2ECTAE3HP8PmpptcwICp4L5I9n9oepYUflEaaUOoYly_ieQpNEhAcdM_0XMMq07BGM1Yqh9QDeVnsEiThvxkoBRdX2lZZnukql4xEs_FTiGjapW0Kg",
  //       "scope": "email profile https://www.googleapis.com/auth/userinfo.email openid https://www.googleapis.com/auth/userinfo.profile",
  //       "login_hint": "AJDLj6LnlZnzrxkLvL97-1S_VZNnCe6eRUyhx5XUx2mybZ-XsdNTbGelgAByn-pVvkzA51Uuobf82vbLVLySsnPp4pGETLFhqC05AQqI_mKKQCeEZvBJI_w",
  //       "expires_in": 3599,
  //       "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRlOTU1NmFkNDY4MDMxMmMxMTdhZmFlZjI5MjBmNWY5OWE0Yzc5ZmQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMzExMTkyOTIzOTU3LWRrbG5rcTR2bGMwZmNybmNidDM3djFqa2tiYjFxdmIxLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXVkIjoiMzExMTkyOTIzOTU3LWRrbG5rcTR2bGMwZmNybmNidDM3djFqa2tiYjFxdmIxLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwic3ViIjoiMTA2MTg2OTk2MTU0NTU4NDYzMTc1IiwiZW1haWwiOiJkb2Rqb3kwM0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6ImFEOGZFeWRkMFc1UGhVY2xETm5nX2ciLCJuYW1lIjoiMDMgZG9kam95IiwicGljdHVyZSI6Imh0dHBzOi8vbGg1Lmdvb2dsZXVzZXJjb250ZW50LmNvbS8tek02QjE0bmZFYTgvQUFBQUFBQUFBQUkvQUFBQUFBQUFBQUEvQU1adXVjbnJtcnliS3FLd1JKbTdwY3pnNGtCeXc0MkNYZy9zOTYtYy9waG90by5qcGciLCJnaXZlbl9uYW1lIjoiMDMiLCJmYW1pbHlfbmFtZSI6ImRvZGpveSIsImxvY2FsZSI6InpoLUNOIiwiaWF0IjoxNjE4OTcwMjUxLCJleHAiOjE2MTg5NzM4NTEsImp0aSI6ImU1M2UxYzZmYjBjNTI3NTUzYjliMjU0ZWUwYzliZDFiMWUyNGQ2MDAifQ.j0ujNtKOGsNO3qQECjNYUJVFjFQhSrU5LoYGLYYqGDRsGMTuX5N4l4G32NO_8Rm3TDe1g0RidH7Dvw_bFdV-K0JuonpbsIMKUioj0M6ukKNBtbfvMg_7o9xo_OlF64qoth69-MmpbCkL2U5G0CB1ItutkdDVDyBkYfnqRynickgoUb_9Hpq1fxg2zOR-LmW6lmziQ8gJ_f7o17XiDrk-aRl4d7nLT-lI0bH59oajgHBhAyc2mk0msdn9dqgFDPBV3PQdishk7FXF0Jf1-DrtDUnBVenDbrHKq8l5AnomfFCx6O4YPcfCKtgjCh7HC2yJ0rX_QEfow9wOWo1rUtIZgA",
  //       "session_state": {
  //           "extraQueryParams": {
  //               "authuser": "0"
  //           }
  //       },
  //       "first_issued_at": 1618970251755,
  //       "expires_at": 1618973850755,
  //       "idpId": "google"
  //   },
  //   "gt": {
  //       "GS": "106186996154558463175",
  //       "Te": "03 dodjoy",
  //       "rU": "03",
  //       "mS": "dodjoy",
  //       "zJ": "https://lh5.googleusercontent.com/-zM6B14nfEa8/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucnrmrybKqKwRJm7pczg4kByw42CXg/s96-c/photo.jpg",
  //       "Rt": "dodjoy03@gmail.com"
  //   }
  // }
  var id_token = '';
  try {
    var TC = googleUser.tc;
    if(TC) {
      id_token = TC.id_token;
    }
  } catch (error) {
  }
  try {
    var QC = googleUser.qc;
    if(QC) {
      id_token = QC.id_token;
    }
  } catch (error) {
  }
  var authResponse = {
    userID: googleUser.Aa,
    accessToken: id_token,
  };
  login(authResponse, 8);     
}

function onFailure(error) {
  $tool.showError('please login by google!');
}
/**********************************google登录end******************************************/
/**********************************賬號密碼登錄start******************************************/
function loginBypwd() {
  var account = $('#account').val();
  var pwd = $('#pwd').val();
  var paltform = localStorage.getItem('paltform');
  if(account && pwd && paltform) {
    $.get('/php/userLogin.php', {
      account: account,
      pwd: pwd,
      paltform: paltform
    }, function(response) {
      console.log(response);
      var res = JSON.parse(response);
      if(res.status === true) {
        const username = res.data.username;
        const uid = res.data.uid;
        localStorage.setItem('username', username);
        localStorage.setItem('uid', uid);

        initAccount();
        initUserRole();
        initRecharge();

        $('.card').show();
        $('.main-section').hide();
      } else {
        $tool.showError('賬號密碼登錄失敗!');
      }
    });
  } else {
    $tool.showError('請輸入賬號密碼!');
  }
}
/**********************************賬號密碼登錄end******************************************/
/**********************************登录start******************************************/
function login(authResponse, openType) {
  var paltform = localStorage.getItem('paltform');
  const requestData = {
    userID: authResponse.userID,
    accessToken:authResponse.accessToken,
    openType: openType,
    paltform: paltform
  };
  $.get('/php/login.php', requestData, function(response) {
    // console.log(response);
    // {
    //   "status": true,
    //   "data": {
    //     "username": "pq40990406",
    //     "uid": "6440478",
    //     "isGuest": 0,
    //     "openType": 6,
    //     "otherAccountName": "Liu Hem",
    //     "isNewUser": 0,
    //     "bindInfo": {
    //       "bindFB": {
    //         "isBind": 1,
    //         "otherAccountName": "Liu Hem"
    //       },
    //       "bindGameCenter": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindGoogle": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindEmail": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindNaver": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindTwitter": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindLine": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindVK": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "signApple": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       },
    //       "bindPlay": {
    //         "isBind": 0,
    //         "otherAccountName": ""
    //       }
    //     },
    //     "noLoginLongTime": 0,
    //     "isTrash": 0
    //   },
    //   "message": ""
    // }
    var res = JSON.parse(response);
    if(res.status === true) {
      const username = res.data.username;
      const uid = res.data.uid;
      const bindinfo = res.data.bindInfo;
      const bindFB = bindinfo.bindFB;
      const bindGoogle = bindinfo.bindGoogle;

      localStorage.setItem('bindFB', JSON.stringify(bindFB));
      localStorage.setItem('bindGoogle', JSON.stringify(bindGoogle));
      localStorage.setItem('openType', openType);
      localStorage.setItem('username', username);
      localStorage.setItem('uid', uid);

      initAccount();
      initUserRole();
      initRecharge();

      $('.card').show();
      $('.main-section').hide();
    } else {
      $tool.showError('login fail!');
    }
  });
}
/**********************************登录end******************************************/
/**********************************以下为普通逻辑方法******************************************/
function form_validate() {
  var type = $tool.getQuery('type');
  if (!$('#facebook_username').val().trim() && !$('#google_username').val().trim()) {
    if(!type) {
      return "請使用FaceBook或Google賬號登錄";
    }
  }
  if (!$('#username').val().trim() || !$('#userId').val().trim()) {
    return "當前帳號不支持";
  }
  if (!$('#server').val() || !$("#server").find("option:selected").text().trim()) {
    return "請選擇正確的伺服器";
  }
  if (!$("#role_name").val().trim() || !$("#role_id").val().trim() || !$("#role_level").val().trim()) {
    return "為查詢到當前伺服器存在角色";
  }
  if (!$('#recharge').val() || !$("#recharge").find("option:selected").text().trim()) {
    return "請選擇正確的充值檔位或商品";
  }
  return true;
}

function MapToObj(strMap) {
  let obj = Object.create(null);
  for (let [k, v] of strMap) {
    obj[k] = v;
  }
  return obj;
}

function ObjToMap(obj) {
  let strMap = new Map();
  for (let k of Object.keys(obj)) {
    strMap.set(k, obj[k]);
  }
  return strMap;
}

function getCurPaltform() {
  var paltforms = document.getElementsByName('paltform');
  for(var i = 0; i < paltforms.length; i++) {
    var _p = paltforms[i].parentNode;
    if(_p.className.search('active') != -1) {
      return _p.ariaValueText;
    }
  }
}